package cn.lg.soar.common.algorithm;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 数据签名器（使用Hmac算法）
 * @author luguoxiang 469599794@qq.com
 * @Date: 2025/5/19 9:10
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class HmacSigner implements Signer {
    private final String algorithm;
    private final SecretKeySpec keySpec;

    public HmacSigner(String algorithm, String secret) {
        this.algorithm = algorithm;
        this.keySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm);
    }

    @Override
    public byte[] sign(byte[] data) {
        Mac mac;
        try {
            mac = Mac.getInstance(algorithm);
            mac.init(keySpec);
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return mac.doFinal(data);
    }

    public byte[] sign(String data) {
        Mac mac;
        try {
            mac = Mac.getInstance(algorithm);
            mac.init(keySpec);
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
    }

    public static HmacSigner sha256(String secret) {
        return new HmacSigner("HmacSHA256", secret);
    }

    public static HmacSigner sha384(String secret) {
        return new HmacSigner("HmacSHA384", secret);
    }

    public static HmacSigner sha512(String secret) {
        return new HmacSigner("HmacSHA512", secret);
    }

}